//
//  ViewController.m
//  UI19_Work 汽车之家
//
//  Created by dllo on 16/8/9.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "ViewController.h"
#import "AllCar.h"
#import "SmallModel.h"
#import "MainCollectionModel.h"
#import "MyCollectionViewCell.h"
#import "MyTableViewCell.h"
#import "HotCar.h"
#import "HotCollectionViewCell.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *smallArray;
@property (nonatomic, strong) NSMutableArray *letterArray;

@property (nonatomic, strong) UICollectionView *mainCollectionView;
@property (nonatomic, strong) NSMutableArray *mainArray;

@property (nonatomic, strong) UICollectionView *hotCollectionView;
@property (nonatomic, strong) NSMutableArray *hotArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self createData];
    [self createMainData];
    [self createHotData];
    
    [self createTableView];
    [self createMainCollectionView];
    [self createHotCollectionView];
    
}
- (void)createHotData {
    self.hotArray = [NSMutableArray array];
    NSURL *url = [NSURL URLWithString:@"http://223.99.255.20/cars.app.autohome.com.cn/dealer_v6.0.0/dealer/hotbrands-pm2.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = dataDic[@"result"][@"list"];
        for (NSDictionary *dic in array) {
            HotCar *hotCar = [HotCar hotCarWithDic:dic];
            [self.hotArray addObject:hotCar];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.hotCollectionView reloadData];
            });
        }
    }];
    NSLog(@"%@", self.hotArray);

//    NSString *path = [[NSBundle mainBundle] pathForResource:@"hot" ofType:@".json"];
//    NSData *hotData = [NSData dataWithContentsOfFile:path];
//    NSError *error = nil;
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:hotData options:NSJSONReadingMutableContainers error:&error];
//    NSArray *array = dic[@"result"][@"list"];
//    self.hotArray = [NSMutableArray array];
//    for (NSDictionary *dic in array) {
//        HotCar *hot = [HotCar hotCarWithDic:dic];
//        [self.hotArray addObject:hot];
//    }
}

- (void)createHotCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.view.bounds.size.width / 5, 90);
    
    self.hotCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 30, self.view.bounds.size.width, 180) collectionViewLayout:layout];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    self.hotCollectionView.delegate = self;
    self.hotCollectionView.dataSource = self;
    self.hotCollectionView.backgroundColor = [UIColor whiteColor];
    [self.tableView.tableHeaderView addSubview:self.hotCollectionView];
    [self.hotCollectionView registerClass:[HotCollectionViewCell class] forCellWithReuseIdentifier:@"thiredReuse"];
}

- (void)createMainData {
    self.mainArray = [NSMutableArray array];
    NSURL *url = [NSURL URLWithString:@"http://adnewnc.app.autohome.com.cn/autov5.7.0/ad/infoad.ashx?version=6.2.0&platform=2&appid=2&networkid=0&adtype=1&provinceid=210000&cityid=0&lng=121.550752&lat=38.889715&gps_city=210200&pageid=9ff27f0e-1584-4db6-8d1d-4c82412f5cb9&isretry=0&deviceid=864895028079653"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = dic[@"result"][@"list"];
        for (NSDictionary *dic in array) {
            MainCollectionModel *main = [MainCollectionModel mainCollectionModelDic:dic];
            [self.mainArray addObject:main];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mainCollectionView reloadData];
            });
            
        }
    }];
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"main" ofType:@".json"];
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    NSError *error = nil;
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//    self.mainArray = [NSMutableArray array];
//    NSArray *array = dic[@"result"][@"list"];
//    for (NSDictionary *dic in array) {
//        MainCollectionModel *mainModel = [MainCollectionModel mainCollectionModelDic:dic];
//        [self.mainArray addObject:mainModel];
//    }
}

- (void)createMainCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.view.bounds.size.width / 3, 200);
    
    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 240, self.view.bounds.size.width, 200) collectionViewLayout:layout];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    self.mainCollectionView.backgroundColor = [UIColor whiteColor];
    [self.tableView.tableHeaderView addSubview:self.mainCollectionView];
    [self.mainCollectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"secReuse"];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([collectionView isEqual:self.hotCollectionView]) {
        return self.hotArray.count;
    } else {
    return self.mainArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual:self.hotCollectionView]) {
        HotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"thiredReuse" forIndexPath:indexPath];
        cell.picImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self.hotArray[indexPath.row] img]]]];
        cell.titleLabel.text = [self.hotArray[indexPath.row] name];
        return cell;
    } else {
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"secReuse" forIndexPath:indexPath];
    cell.titleLabel.text = [self.mainArray[indexPath.row] seriesname];
    cell.picImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self.mainArray[indexPath.row] img]]]];
    return cell;
    }
}
// 利用异步请求
- (void)createData {
    self.dataArray = [NSMutableArray array];
    self.smallArray = [NSMutableArray array];
    self.letterArray = [NSMutableArray array];
    NSURL *url = [NSURL URLWithString:@"http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635580073583652962.html"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *error = nil;
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            NSArray *array = dataDic[@"result"][@"brandlist"];
            for (NSDictionary *dic in array) {
                [self.letterArray addObject:dic[@"letter"]];
                SmallModel *small = [SmallModel smallModelWithDictionary:dic];
                [_smallArray addObject:small];
                for (NSDictionary *dic in small.list) {
                    AllCar *allCar = [AllCar allCarWithDictionary:dic];
                    [self.dataArray addObject:allCar];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                    
                }}
        });
}];
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"Car" ofType:@".json"];
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    NSError *error = nil;
//    NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//    self.dataArray = [NSMutableArray array];
//    self.smallArray = [NSMutableArray array];
//    self.letterArray = [NSMutableArray array];
//    NSArray *array = dataDic[@"result"][@"brandlist"];
//    for (NSDictionary *dic in array) {
//        [self.letterArray addObject:dic[@"letter"]];
//        SmallModel *small = [SmallModel smallModelWithDictionary:dic];
//        [_smallArray addObject:small];
//        for (NSDictionary *dic in small.list) {
//            AllCar *allCar = [AllCar allCarWithDictionary:dic];
//            [self.dataArray addObject:allCar];
        
    
}

- (void)createTableView {
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.rowHeight = 80;
    [self.view addSubview:_tableView];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 440)];
    self.tableView.tableHeaderView = headView;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 210, self.view.frame.size.width, 30)];
    titleLabel.text = @"主打车";
    [self.tableView.tableHeaderView addSubview:titleLabel];
    UILabel *hotLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width, 30)];
    hotLable.text = @"热门品牌";
    [self.tableView.tableHeaderView addSubview:hotLable];
    [_tableView registerClass:[MyTableViewCell class] forCellReuseIdentifier:@"reuse"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.smallArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.smallArray[section] list].count;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.letterArray;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.letterArray[section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    NSArray *array = [self.smallArray[indexPath.section] list];
    cell.titleLabel.text = array[indexPath.row][@"name"];
    cell.picImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:array[indexPath.row][@"imgurl"]]]];
    return cell;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
